package icegps.com.pingdj.activity.settingactivity;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import icegps.com.pingdj.R;
import icegps.com.pingdj.activity.BaseActivity;
import icegps.com.pingdj.bean.PickerBean;
import icegps.com.pingdj.bean.DeviceStatus;
import icegps.com.pingdj.data.ble.WriteHelper;
import icegps.com.pingdj.dialog.BottomDialog;
import icegps.com.pingdj.dialog.DialogPicker;
import icegps.com.pingdj.listener.OnUnitIndexListener;
import icegps.com.pingdj.utils.UnitUtils;
import icegps.com.pingdj.utils.Utils;
import icegps.com.pingdj.view.ValueTextView;

/**
 * Created by 111 on 2018/3/16.
 */

public class SystemSettingActivity extends BaseActivity implements OnUnitIndexListener {
    @BindView(R.id.ll_ins_one)
    LinearLayout llInsOne;
    @BindView(R.id.rb_ins_one)
    RadioButton rbInsOne;
    @BindView(R.id.ll_ins_two)
    LinearLayout llInsTwo;
    @BindView(R.id.rb_ins_three)
    RadioButton rbInsThree;
    @BindView(R.id.ll_ins_three)
    LinearLayout llInsThree;
    @BindView(R.id.ll_area)
    LinearLayout llArea;
    @BindView(R.id.ll_height)
    LinearLayout llHeight;
    @BindView(R.id.ll_length)
    LinearLayout llLength;
    @BindView(R.id.ll_speed)
    LinearLayout llSpeed;
    @BindView(R.id.ll_volume)
    LinearLayout llVolume;
    @BindView(R.id.ll_antenna_location)
    LinearLayout llAntennaLocation;
    @BindView(R.id.ll_control_test)
    LinearLayout llControlTest;
    @BindView(R.id.ll_balance_calibration)
    LinearLayout llBalanceCalibration;
    @BindView(R.id.ll_restore_the_factory)
    LinearLayout llRestoreTheFactory;
    @BindView(R.id.ll_about)
    LinearLayout llAbout;
    @BindView(R.id.tv_area)
    TextView tvArea;
    @BindView(R.id.tv_height)
    TextView tvHeight;
    @BindView(R.id.tv_length)
    TextView tvLength;
    @BindView(R.id.tv_speed)
    TextView tvSpeed;
    @BindView(R.id.tv_volume)
    TextView tvVolume;
    @BindView(R.id.ll_radio)
    LinearLayout llRadio;
    @BindView(R.id.ll_work_width)
    LinearLayout llWorkWidth;
    @BindView(R.id.ll_work_accuracy)
    LinearLayout llWorkAccuracy;
    @BindView(R.id.rb_ins_two)
    RadioButton rbInsTwo;
    @BindView(R.id.tv_radio)
    TextView tvRadio;
    @BindView(R.id.tv_work_width)
    ValueTextView tvWorkWidth;
    @BindView(R.id.tv_work_width_unit)
    TextView tvWorkWidthUnit;
    @BindView(R.id.tv_work_accuracy)
    TextView tvWorkAccuracy;
    @BindView(R.id.tv_work_accuracy_unit)
    TextView tvWorkAccuracyUnit;
    @BindView(R.id.tv_antenna_location)
    TextView tvAntennaLocation;
    @BindView(R.id.tv_antenna_location_unit)
    TextView tvAntennaLocationUnit;
    private BottomDialog bottomDialog;
    private ArrayList<String> workAccuracys;
    private DialogPicker dialogPicker;

    @Override
    protected String setTitle() {
        return getString(R.string.system_settings);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_system_setting;
    }

    @Override
    protected void init() {
        WriteHelper.write(WriteHelper.GET_RADIO);
        setConfig();
        setInsMode(deviceStatus.getInsMode());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.ll_radio, R.id.ll_work_width, R.id.ll_ins_one, R.id.ll_ins_two, R.id.ll_ins_three, R.id.ll_area, R.id.ll_height, R.id.ll_length, R.id.ll_speed, R.id.ll_volume, R.id.ll_antenna_location, R.id.ll_control_test, R.id.ll_balance_calibration, R.id.ll_restore_the_factory, R.id.ll_about, R.id.ll_work_accuracy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_radio: //频道设置
                setRadio();
                break;
            case R.id.ll_work_accuracy:
                setWorkAccuracy();//平地精度
                break;
            case R.id.ll_work_width://作业宽度
                setWorkWidth();
                break;
            case R.id.ll_ins_one://单通道
                WriteHelper.write(WriteHelper.SETINSMODE + 0);
                changeRbWithInsMode(R.id.rb_ins_one);
                break;
            case R.id.ll_ins_two://双通道两端
                WriteHelper.write(WriteHelper.SETINSMODE + 1);
                changeRbWithInsMode(R.id.rb_ins_two);
                break;
            case R.id.ll_ins_three://双通道平衡
                WriteHelper.write(WriteHelper.SETINSMODE + 2);
                changeRbWithInsMode(R.id.rb_ins_three);
                break;
            case R.id.ll_area://面积单位设置
                setAreaUnit();
                break;
            case R.id.ll_height://高度单位设置
                setHeightUnit();
                break;
            case R.id.ll_length://长度单位设置
                setLengthUnit();
                break;
            case R.id.ll_speed://速度单位设置
                setSpeedUnit();
                break;
            case R.id.ll_volume://体积单位设置
                setVolumeUnit();
                break;
            case R.id.ll_antenna_location://天线位置
                setAntennaLocation();
                break;
            case R.id.ll_control_test://控制测试
                startActivity(ControlTestActivity.class);
                break;
            case R.id.ll_balance_calibration://平衡校准
                if (deviceStatus.getInsMode() == 0) {
                    Utils.showToast(getString(R.string.single_channel_does_not_need_calibration));
                } else {
                    startActivity(BalanceCalibrationActivity.class);
                }
                break;
            case R.id.ll_restore_the_factory:
                restoreTheFactory();//恢复出厂
                break;
            case R.id.ll_about://关于我们
                startActivity(AboutActivity.class);
                break;
        }
    }

    private void setWorkAccuracy() {
        workAccuracys = new ArrayList<>();
        for (int i = 5; i <= 100; i++) {
            if (i % 5 == 0) {
                workAccuracys.add(i / 10f + "");
            }
        }
        String[] values = new String[workAccuracys.size()];
        workAccuracys.toArray(values);
        int index = workAccuracys.indexOf(deviceStatus.getWorkAccuracy());
        if (index == -1) index = 1;
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, index));
        arrayList.add(new PickerBean(new String[]{tvWorkAccuracyUnit.getText().toString()}, DialogPicker.TEXT_VIEW, 0));
        showSel(arrayList, llWorkAccuracy);
    }

    private void restoreTheFactory() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.factory_data_reset)
                .setMessage(R.string.factory_data_reset_hint)
                .setNegativeButton(R.string.no, null)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        WriteHelper.write(WriteHelper.RESTORE);
                        resetConfig();
                        Utils.showToast(getString(R.string.factory_data_reset_success));
                    }
                }).show();
    }

    public void resetConfig() {
        DeviceStatus.initConfig();
        setConfig();
    }

    private void setInsMode(int insMode) {
        switch (insMode) {
            case 0:
                changeRbWithInsMode(R.id.rb_ins_one);
                break;
            case 1:
                changeRbWithInsMode(R.id.rb_ins_two);
                break;
            case 2:
                changeRbWithInsMode(R.id.rb_ins_three);
                break;
        }
    }

    private void changeRbWithInsMode(int id) {
        if (rbInsOne.isChecked() && id == R.id.rb_ins_one) return;
        if (rbInsTwo.isChecked() && id == R.id.rb_ins_two) return;
        if (rbInsThree.isChecked() && id == R.id.rb_ins_three) return;
        rbInsOne.setChecked(id == R.id.rb_ins_one);
        rbInsTwo.setChecked(id == R.id.rb_ins_two);
        rbInsThree.setChecked(id == R.id.rb_ins_three);
    }

    private void setWorkWidth() {
        String workWidth = deviceStatus.getWorkWidth() + "";
        String[] split = workWidth.split("\\.");
        workWidth = "";
        workWidth += split[0] + split[1];
        while (workWidth.length() < 3) workWidth += "0";
        String[] values = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        PickerBean p1 = new PickerBean(values, DialogPicker.PICKER_VIEW, Integer.parseInt(String.valueOf(workWidth.charAt(0))));
        PickerBean p2 = new PickerBean(new String[]{"."}, DialogPicker.TEXT_VIEW, 0);
        PickerBean p3 = new PickerBean(values, DialogPicker.PICKER_VIEW, Integer.parseInt(String.valueOf(workWidth.charAt(1))));
        PickerBean p4 = new PickerBean(values, DialogPicker.PICKER_VIEW, Integer.parseInt(String.valueOf(workWidth.charAt(2))));
        PickerBean p5 = new PickerBean(new String[]{tvWorkWidthUnit.getText().toString()}, DialogPicker.TEXT_VIEW, 0);
        arrayList.add(p1);
        arrayList.add(p2);
        arrayList.add(p3);
        arrayList.add(p4);
        arrayList.add(p5);
        showSel(arrayList, llWorkWidth);
    }

    private void setAntennaLocation() {
        String s = deviceStatus.getAntennaLocation() + "";
        int[] indexs = new int[6];
        if (s.contains("-")) {
            indexs[0] = 1;
            s = s.replace("-", "");
        } else {
            indexs[0] = 0;
        }
        for (int i = 0; i < s.length(); i++) {
            String ss = String.valueOf(s.charAt(s.length() - 1 - i));
            if (ss.equals(".")) {
                indexs[indexs.length - 2 - i] = 0;
            } else {
                indexs[indexs.length - 2 - i] = Integer.parseInt(ss);
            }
        }
        String[] symbol = {"+", "-"};
        String[] values = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        PickerBean p1 = new PickerBean(symbol, DialogPicker.PICKER_VIEW, indexs[0]);
        PickerBean p2 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[1]);
        PickerBean p3 = new PickerBean(new String[]{"."}, DialogPicker.TEXT_VIEW, indexs[2]);
        PickerBean p4 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[3]);
        PickerBean p5 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[4]);
        PickerBean p6 = new PickerBean(new String[]{tvAntennaLocationUnit.getText().toString()}, DialogPicker.TEXT_VIEW, indexs[5]);
        arrayList.add(p1);
        arrayList.add(p2);
        arrayList.add(p3);
        arrayList.add(p4);
        arrayList.add(p5);
        arrayList.add(p6);
        showSel(arrayList, llAntennaLocation);
    }

    private void setRadio() {
        if (deviceStatus.getMaxRadio() == 0 || deviceStatus.getMinRadio() == 0 || deviceStatus.getCurrentRadio() == 0) {
            Utils.showToast(getString(R.string.no_get_radio_data));
            return;
        }
        ArrayList<String> value = new ArrayList<>();
        int maxRadio = deviceStatus.getMaxRadio();
        int minRadio = deviceStatus.getMinRadio();
        int currentRadio = deviceStatus.getCurrentRadio();
        for (int i = minRadio; i <= maxRadio; i++) {
            value.add(String.valueOf(i));
        }
        int index = value.indexOf(String.valueOf(currentRadio));
        String[] values = new String[value.size()];
        value.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, index));
        showSel(arrayList, llRadio);
    }

    //单位设置start
    private void setVolumeUnit() {
        ArrayList<String> unitValues = UnitUtils.getUnitValues(UnitUtils.VOLUME);
        String[] values = new String[unitValues.size()];
        unitValues.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, deviceStatus.getVolume()));
        showSel(arrayList, llVolume);
    }

    private void setSpeedUnit() {
        ArrayList<String> unitValues = UnitUtils.getUnitValues(UnitUtils.SPEED);
        String[] values = new String[unitValues.size()];
        unitValues.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, deviceStatus.getSpeed()));
        showSel(arrayList, llSpeed);
    }

    private void setLengthUnit() {
        ArrayList<String> unitValues = UnitUtils.getUnitValues(UnitUtils.LENGTH);
        String[] values = new String[unitValues.size()];
        unitValues.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, deviceStatus.getLength()));
        showSel(arrayList, llLength);
    }

    private void setHeightUnit() {
        ArrayList<String> unitValues = UnitUtils.getUnitValues(UnitUtils.HEIGHT);
        String[] values = new String[unitValues.size()];
        unitValues.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, deviceStatus.getHeight()));
        showSel(arrayList, llHeight);
    }

    private void setAreaUnit() {
        ArrayList<String> unitValues = UnitUtils.getUnitValues(UnitUtils.AREA);
        String[] values = new String[unitValues.size()];
        unitValues.toArray(values);
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        arrayList.add(new PickerBean(values, DialogPicker.PICKER_VIEW, deviceStatus.getArea()));
        showSel(arrayList, llArea);
    }

    //单位设置end
    private void showSel(ArrayList<PickerBean> arrayList, View view) {
        dialogPicker.setLayoutOrder(arrayList, view.getId());
        dialogPicker.setOnUnitIndexListener(this);
        dialogPicker.show();
    }

    @Override
    public void onUnitIndex(int viewId, int[] selIndex, String[] values) {
        switch (viewId) {
            case R.id.ll_area: {
                deviceStatus.setArea(selIndex[0]);
            }
            break;
            case R.id.ll_height: {
                deviceStatus.setHeight(selIndex[0]);
            }
            break;
            case R.id.ll_length: {
                deviceStatus.setLength(selIndex[0]);
            }
            break;
            case R.id.ll_speed: {
                deviceStatus.setSpeed(selIndex[0]);
            }
            break;
            case R.id.ll_volume: {
                deviceStatus.setVolume(selIndex[0]);
            }
            break;
            case R.id.ll_radio: {
                WriteHelper.write(WriteHelper.SET_RADIO + (selIndex[0] + 1));
                deviceStatus.setCurrentRadio(selIndex[0] + 1);
            }
            break;
            case R.id.ll_work_accuracy: {
                String s = workAccuracys.get(selIndex[0]);
                float workAccuracy = Float.parseFloat(s);
                deviceStatus.setWorkAccuracy(workAccuracy + "");
                WriteHelper.write(WriteHelper.SET_ACCURACY + workAccuracy * 10);
            }
            break;
            case R.id.ll_work_width: {
                String value = "";
                for (String s : values) {
                    value += s;
                }
                if (TextUtils.isEmpty(value)) value = "0";
                float workWidth = Float.parseFloat(value);
                deviceStatus.setWorkWidth(workWidth);
                WriteHelper.write(WriteHelper.SET_BUCKETW + value);
                setConfig();
            }
            break;
            case R.id.ll_antenna_location: {
                String value = "";
                for (String s : values) {
                    value += s;
                }
                if (TextUtils.isEmpty(value)) value = "0";
                float antennaLocation = Float.parseFloat(value);
                WriteHelper.write(WriteHelper.SET_ANTENNAP + value);
                deviceStatus.setAntennaLocation(antennaLocation);
                setConfig();
            }
            break;
        }
        setConfig();
    }


    private void setConfig() {
        dialogPicker = new DialogPicker(activity);
        bottomDialog = new BottomDialog(activity);
        tvArea.setText(UnitUtils.index2Value(UnitUtils.AREA, deviceStatus.getArea()));
        tvHeight.setText(UnitUtils.index2Value(UnitUtils.HEIGHT, deviceStatus.getHeight()));
        tvLength.setText(UnitUtils.index2Value(UnitUtils.LENGTH, deviceStatus.getLength()));
        tvSpeed.setText(UnitUtils.index2Value(UnitUtils.SPEED, deviceStatus.getSpeed()));
        tvVolume.setText(UnitUtils.index2Value(UnitUtils.VOLUME, deviceStatus.getVolume()));

        tvRadio.setText(deviceStatus.getCurrentRadio() + "");
        tvWorkAccuracy.setText(deviceStatus.getWorkAccuracy());

        if (deviceStatus.getWorkWidth() > 10) {
            deviceStatus.setWorkWidth(9.99f);
        }
        if (deviceStatus.getWorkWidth() < -10) {
            deviceStatus.setWorkWidth(-9.99f);
        }
        tvWorkWidth.setText(deviceStatus.getWorkWidth() + "");

        if (deviceStatus.getAntennaLocation() > 10) {deviceStatus.setAntennaLocation(9.99f);
        }
        if (deviceStatus.getAntennaLocation() < -10) {
            deviceStatus.setAntennaLocation(-9.99f);
        }
        tvAntennaLocation.setText(deviceStatus.getAntennaLocation() + "");
    }


    @Override
    public void onAnalysisAscDeviceStatus(DeviceStatus settingConfig) {
        super.onAnalysisAscDeviceStatus(settingConfig);
        setInsMode(settingConfig.getInsMode());
        setConfig();
    }


}
